<template>
  <div class="video-player-container">
    <div ref="artRef" class="artplayer-app"></div>
    <div class="barrage-bar">
      <input v-model="danmuText" placeholder="发个弹幕见证下" />
      <button class="send-btn" @click="sendDanmu">发送</button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import Hls from 'hls.js';

import Artplayer from 'artplayer';
import artplayerPluginDanmuku from 'artplayer-plugin-danmuku';

const artRef = ref<HTMLDivElement | null>(null);
const props = defineProps<{ url: string }>();

const danmuText = ref('');
let art: Artplayer | null = null;

onMounted(() => {
    console.log('VideoPlayer mounted: ' + props.url);
  art = new Artplayer({
    container: artRef.value!,
    url: props.url,
    fullscreen: true,
    fullscreenWeb: true,
    customType: {
      m3u8: (video: HTMLVideoElement) => {
        if (Hls.isSupported()) {
          const hls = new Hls();
          console.log('Using Hls.js to play m3u8');
          hls.loadSource(props.url);
          hls.attachMedia(video);
          return hls;
        }else {
          video.src = props.url;
        }
      },
    },
    autoplay: false,
    theme: '#e91e63',
    poster: '', // 可设封面
    isLive: false,
    volume: 0.8,
    // danmuku: {
    //   // 初始化弹幕插件
    //   // 可用 artplayer-plugin-danmuku
    //   // 这里演示本地模式
    //   danmuku: [],
    //   speed: 5,
    //   opacity: 1,
    //   fontSize: 25,
    //   color: '#fff',
    //   mode: 0,
    //   margin: [10, 100],
    //   useWorker: false,
    // },
    plugins: [
      artplayerPluginDanmuku({
        danmuku: [],
        speed: 5,
        opacity: 1,
        fontSize: 25,
        color: '#fff',
        margin: [10, 100],
      }),
    ],
  });
});

onUnmounted(() => {
  art?.destroy();
});

function sendDanmu() {
  if (danmuText.value.trim() && art) {
    art.plugins.artplayerPluginDanmuku.emit({
      text: danmuText.value,
      color: '#ffff00',
      border: true,
      time: art.currentTime,
    });
    danmuText.value = '';
  }
}
</script>

<style scoped>
.video-player-container {
  background: #181818;
  padding: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.artplayer-app {
  width: 960px;
  height: 540px;
  margin: 0 auto;
}
.barrage-bar {
  display: flex;
  margin-top: 8px;
  width: 960px;
}
.barrage-bar input {
  flex: 1;
  height: 32px;
  border-radius: 4px;
  border: 1px solid #aaa;
  padding: 0 8px;
  margin-right: 8px;
}
.send-btn {
  background: #ec407a;
  color: #fff;
  border: none;
  border-radius: 4px;
  width: 60px;
  height: 32px;
  cursor: pointer;
}
</style>